<?php
namespace app\controller;

use support\Request;
use support\Db;

class CategoryController
{
    /**
     * 验证用户是否有权限操作该账本
     */
    private function checkBookPermission($bookId, $userId)
    {
        return Db::table('account_book_users')
            ->where('book_id', $bookId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->exists();
    }

    /**
     * 创建分类
     */
    public function create(Request $request)
    {
        try {
            $data = [
                'book_id' => $request->post('book_id'),
                'name' => $request->post('name'),
                'type' => $request->post('type'), // 1支出 2收入
                'color' => $request->post('color', '#666666'),
                'sort' => $request->post('sort', 0),
                'created_at' => date('Y-m-d H:i:s')
            ];

            // 验证
            if (empty($data['book_id']) || empty($data['name']) || empty($data['type'])) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($data['book_id'], $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            $id = Db::table('categories')->insertGetId($data);

            return json([
                'code' => 0,
                'msg' => '创建成功',
                'data' => ['id' => $id]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取分类列表
     */
    public function list(Request $request)
    {
        try {
            $bookId = $request->get('book_id');
            $type = $request->get('type'); // 可选参数，筛选收入或支出

            if (empty($bookId)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($bookId, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            $query = Db::table('categories')
                ->where('book_id', $bookId)
                ->where('status', 1);

            // 如果指定了类型，则筛选
            if ($type) {
                $query->where('type', $type);
            }

            $list = $query->orderBy('sort', 'asc')
                ->orderBy('id', 'asc')
                ->get();

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 更新分类
     */
    public function update(Request $request)
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 获取分类信息
            $category = Db::table('categories')
                ->where('id', $id)
                ->where('status', 1)
                ->first();

            if (!$category) {
                return json([
                    'code' => 404,
                    'msg' => '分类不存在'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($category->book_id, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            $data = [
                'name' => $request->post('name'),
                'color' => $request->post('color'),
                'sort' => $request->post('sort'),
                'updated_at' => date('Y-m-d H:i:s')
            ];

            // 过滤空值
            $data = array_filter($data, function($value) {
                return $value !== null;
            });

            Db::table('categories')
                ->where('id', $id)
                ->update($data);

            return json([
                'code' => 0,
                'msg' => '更新成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 删除分类（软删除）
     */
    public function delete(Request $request)
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 获取分类信息
            $category = Db::table('categories')
                ->where('id', $id)
                ->where('status', 1)
                ->first();

            if (!$category) {
                return json([
                    'code' => 404,
                    'msg' => '分类不存在'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($category->book_id, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            Db::table('categories')
                ->where('id', $id)
                ->update([
                    'status' => 0,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

            return json([
                'code' => 0,
                'msg' => '删除成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 更新分类排序
     */
    public function sort(Request $request)
    {
        try {
            $data = $request->post();
            if (empty($data['categories']) || !is_array($data['categories'])) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 获取所有分类ID
            $categoryIds = array_column($data['categories'], 'id');
            
            // 验证这些分类是否属于同一个账本
            $categories = Db::table('categories')
                ->whereIn('id', $categoryIds)
                ->where('status', 1)
                ->get();

            if (count($categories) !== count($categoryIds)) {
                return json([
                    'code' => 400,
                    'msg' => '存在无效的分类ID'
                ]);
            }

            // 确保所有分类属于同一个账本
            $bookId = $categories[0]->book_id;
            foreach ($categories as $category) {
                if ($category->book_id !== $bookId) {
                    return json([
                        'code' => 400,
                        'msg' => '分类不属于同一个账本'
                    ]);
                }
            }

            // 验证用户权限
            if (!$this->checkBookPermission($bookId, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            // 批量更新排序
            Db::beginTransaction();
            try {
                foreach ($data['categories'] as $item) {
                    Db::table('categories')
                        ->where('id', $item['id'])
                        ->update([
                            'sort' => $item['sort'],
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                }
                Db::commit();

                return json([
                    'code' => 0,
                    'msg' => '更新成功'
                ]);
            } catch (\Exception $e) {
                Db::rollBack();
                throw $e;
            }
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
} 